package com.codingfly.filter;

import com.codingfly.core.util.ResponseUtils;
import com.codingfly.service.OauthService;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

/**
 * 后端过滤器，主要是web后台管理的过滤器
 */
public class OauthFilter extends OncePerRequestFilter {
    // 白名单URL
    Set<String> whiteListUrls = new HashSet() {{
        add("/oauth/verifyCode");
        add("/oauth/login");
        add("/oauth/register");
        add("heartbeat");
        add("/api/oauth/verifyCode");
        add("/api/oauth/login");
        add("/api/oauth/register");
        add("/api/heartbeat");
    }};

    private OauthService oauthService;

    private byte[] noLoginMsgBytes = "{\"code\":401,\"msg\":\"未登录或者token过期\",\"data\":null}".getBytes();

    public OauthFilter(OauthService oauthService) {
        this.oauthService = oauthService;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
                                    FilterChain filterChain) throws IOException, ServletException {
        String uri = request.getRequestURI();
        if (whiteListUrls.contains(uri)==false) { // 不在白名单的URL都校验
            if (oauthService.checkAccessTokenValid()==false) {
                ResponseUtils.assemblyResponse(noLoginMsgBytes);
                return;
            }
        }
        filterChain.doFilter(request, response);
    }
}